package com.kevinwu.sqlSession;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kevinwu.config.BoundSql;
import com.kevinwu.pojo.Configuation;
import com.kevinwu.pojo.MappedStatement;
import com.kevinwu.utils.GenericTokenParser;
import com.kevinwu.utils.ParameterMapping;
import com.kevinwu.utils.ParameterMappingTokenHandler;
import com.kevinwu.utils.TokenHandler;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutorImpl implements Executor {
    @Override
    public <E> List<E> query(Configuation configuation, MappedStatement mappedStatement, Object... params) throws SQLException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException, IntrospectionException, InvocationTargetException, InstantiationException {

        Connection connection = configuation.getDataSource().getConnection();
        String sql = mappedStatement.getSql();
        BoundSql boundsql = getBoundSql(sql);

        PreparedStatement preparedStatement = connection.prepareStatement(boundsql.getSqlText());
        String parameterType = mappedStatement.getParameterType();
        Class<?> paramterTypeClass = getClassType(parameterType);
        String resultType = mappedStatement.getResultType();
        Class<?> resultTypeClass = getClassType(resultType);

        List<ParameterMapping> parameterMappingList = boundsql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();
            Field declaredField = paramterTypeClass.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object t = params[0];
            Object o = declaredField.get(t);
            preparedStatement.setObject(i+1,o);
        }

        ResultSet resultSet = preparedStatement.executeQuery();
        ArrayList<Object> objects = new ArrayList<>();
        while (resultSet.next()){
            Object o1 = resultTypeClass.newInstance();
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <=metaData.getColumnCount() ; i++) {

                String columnName = metaData.getColumnName(i);
                Object object = resultSet.getObject(columnName);
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o1,object);

            }
            objects.add(o1);
        }
        return (List<E>) objects;
    }

    /**
     * 执行新增、修改、删除操作
     * @param configuation
     * @param mappedStatement
     * @param params
     */
    @Override
    public void executeTest(Configuation configuation, MappedStatement mappedStatement, Object... params) throws SQLException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException {

        //获取数据库连接
        Connection connection = configuation.getDataSource().getConnection();
        String sql = mappedStatement.getSql();
        BoundSql boundsql = getBoundSql(sql);
        //预编译sql
        PreparedStatement preparedStatement = connection.prepareStatement(boundsql.getSqlText());
        String parameterType = mappedStatement.getParameterType();
        Class<?> paramterTypeClass = getClassType(parameterType);

        List<ParameterMapping> parameterMappingList = boundsql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();
            Field declaredField = paramterTypeClass.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object t = params[0];
            Field declaredField1 = t.getClass().getDeclaredField(content);
            declaredField1.setAccessible(true);
            Object o1 = declaredField1.get(t);
            Object o = declaredField.get(t);
            preparedStatement.setObject(i+1,o);
        }

        preparedStatement.execute();

    }

    /**
     * 删除方法
     * @param configuation
     * @param mappedStatement
     * @param params
     * @throws SQLException
     * @throws ClassNotFoundException
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    @Override
    public void deleteTest(Configuation configuation, MappedStatement mappedStatement, Object... params) throws SQLException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException {

        //获取数据库连接
        Connection connection = configuation.getDataSource().getConnection();
        String sql = mappedStatement.getSql();
        BoundSql boundsql = getBoundSql(sql);
        //预编译sql
        PreparedStatement preparedStatement = connection.prepareStatement(boundsql.getSqlText());
        String parameterType = mappedStatement.getParameterType();


        List<ParameterMapping> parameterMappingList = boundsql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();

            preparedStatement.setObject(i+1,params[0]);
        }

        preparedStatement.execute();

    }

    private Class<?> getClassType(String parameterType) throws ClassNotFoundException {

        if(parameterType!=null){
            Class<?> aClass = Class.forName(parameterType);
            return aClass;
        }else{
            return null;
        }
    }

    private BoundSql getBoundSql(String sql) {

        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        String parseSql = genericTokenParser.parse(sql);
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        BoundSql boundSql = new BoundSql(parseSql, parameterMappings);

        return boundSql;
    }
}
